package com.guang.lock.condition.lockconditiontest;

import com.guang.lock.condition.ConditionSetSleepTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lg
 * @Description 测试在唤醒之前发送中断信息
 * @date 2022/10/21 16:45
 */
public class LockConditionInteruptTestOne {
    private final static Logger logger = LoggerFactory.getLogger(LockConditionInteruptTestOne.class);
    static ReentrantLock lock = new ReentrantLock();

    static Condition condition = lock.newCondition();

    static boolean flag = false;

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            lock.lock();
            while (!flag) {
                logger.info("标志位为false，表示当前未修改，那么应该进入到条件队列中来");
                try {
                    condition.await();
                    logger.info("当前线程被唤醒了，再次来进行检查");
                } catch (InterruptedException e) {
                    logger.error("因为抛出了异常，所以这里的线程中断标记会自动清除！JVM机制");
                    logger.error("线程因为中断而进入到条件队列中来，当前线程状态是：{}", Thread.currentThread().isInterrupted());
                    // 抛出这里的异常，因为没有线程处理
                    // e.printStackTrace();
                }
            }
            logger.info("获取得到了锁，来执行临界区代码");
            lock.unlock();
        }, "t1");

        t1.start();

        logger.info("让主线程休息一会儿，让t1线程先启动");
        TimeUnit.MICROSECONDS.sleep(10);

        new Thread(() -> {
            lock.lock();
            while (!flag) {
                logger.info("当前线程来进行修改flag的值");
                try {
                    TimeUnit.SECONDS.sleep(1);
                    flag = true;
                    // 但是没有通知其他线程，而是将其停止掉
                    logger.info("给t1发送中断信号");
                    t1.interrupt();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lock.unlock();

        }, "t2").start();

        logger.info("main线程执行完毕");
    }

}
